# !/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function
import requests
import json
from Cookie import SimpleCookie
import re
from requests_toolbelt import MultipartEncoder


username = 'hjg68666@163.com'
password = 'qq000123'

class PyiCloudSession(requests.Session):
    def __init__(self, service):
        self.service = service
        super(PyiCloudSession, self).__init__()


    def request(self, *args, **kwargs):
        response = super(PyiCloudSession, self).request(*args, **kwargs)
        return response

class Souq:
    def __init__(self):
        self.session = PyiCloudSession(self)
        self.cookies = ''
        self.token = ''

    def cookie(self, tiaojian):
        cookies = SimpleCookie()
        if "set-cookie" in tiaojian:
            tmpCookies = SimpleCookie()
            tmpCookies.load(tiaojian["set-cookie"])
            for cookie in tmpCookies:
                cookies[cookie] = tmpCookies[cookie].value
        return cookies.output(sep=";", attrs=["value"], header="").strip()

    def login1(self):
        url = 'https://sell.souq.com/sell'
        headers = {
            'authority': 'sell.souq.com',
            'method': 'GET',
            'path': '/sell',
            'scheme': 'https',
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.8',
            'cache-control': 'max-age=0',
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36',
            'upgrade-insecure-requests': '1',
        }

        resp = self.session.get(url=url, headers=headers,verify=False)
        tiaojian = resp.headers
        self.cookies = (self.cookies + ';' if self.cookies else '') + self.cookie(tiaojian)
        for item in self.cookies.split(';'):
            if item.startswith(' SCXAT'):
                self.token = item.split('=')[-1].split('+')[0]



    def login(self):
        url = 'https://sell.souq.com/login/validate'
        headers= {
            'authority':'sell.souq.com',
            'method':'POST',
            'path':'/login/validate',
            'scheme':'https',
            'accept':'application/json, text/plain, */*',
            'accept-encoding':'gzip, deflate, br',
            'accept-language':'zh-CN,zh;q=0.8',
            'content-type':'application/x-www-form-urlencoded;charset=UTF-8',
            'origin':'https://sell.souq.com',
            'referer':'https://sell.souq.com/sell',
            'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36',
            'x-requested-with':'XMLHttpRequest',
            'Cookie':self.cookies
        }
        data = {
            'params[email]':username,
            'params[password]':password,
            'params[remember_me]':'off',
            'token':self.token,
        }
        resp = self.session.post(url=url,data=data,headers=headers)
        self.cookies = (self.cookies + ';' if self.cookies else '')+self.cookie(resp.headers)
        print(resp.content)
        for key,value in resp.headers.items():
            print(key,value)
        print(self.cookies)

    def getSellerAllowedToListInfo(self):
        url = 'https://sell.souq.com/inventory/getSellerAllowedToListInfo'
        headers = {
            'authority': 'sell.souq.com',
            'method': 'GET',
            'path': '/inventory/getSellerAllowedToListInfo',
            'scheme': 'https',
            'accept': 'application/json, text/plain, */*',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.8',
            'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'referer': 'https://sell.souq.com/',
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest',
            'Cookie': self.cookies
        }
        resp = self.session.get(url=url,headers=headers,verify=False)
        print(resp.content)

    def step3(self):
        url = 'https://sell.souq.com/inventory/getOffers'
        headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.8',
            'Referer': 'https://sell.souq.com/inventory/inventory-management?tab=all',
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest',
            'Cookies':self.cookies
        }
        params = {
            'size':20,
            'page':0,
            'sortKey':'lastUpdate',
            'sortOrder':'desc',
            'fbs':'no',
            'filters[status]':'available',
        }
        resp = self.session.get(url=url,params=params,headers=headers,timeout = 30)
        print(resp.content)

    def offerlisting(self):
        url = 'https://sell.souq.com/offer-listing/isRestrictedItem?idItemType=487'
        headers = {
            'authority': 'sell.souq.com',
            'method': 'GET',
            'path': '/offer-listing/isRestrictedItem?idItemType=487',
            'scheme': 'https',
            'accept': 'application/json, text/plain, */*',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.8',
            'referer': 'https://sell.souq.com/inventory/search-results/Girls/t=487',
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest',
            'Cookie': self.cookies
        }
        resp = requests.get(url=url,headers=headers,verify=False)
        print(resp.content)
        print(resp.status_code)

    def createItem(self):
        url = 'https://sell.souq.com/inventory/create-item?subcategory=487'
        headers = {
            'authority': 'sell.souq.com',
            'method': 'GET',
            'path': '/inventory/create-item?subcategory=487',
            'scheme': 'https',
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.8',
            'referer': 'https://sell.souq.com/inventory/search-results/Girls/t=487',
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36',
            'upgrade-insecure-requests': '1',
            'Cookie': self.cookies
        }
        resp = requests.get(url=url, headers=headers, verify=False)
        print(resp.content)
        print(resp.status_code)

    def insert(self):
        url = 'https://sell.souq.com/create-item/addItemUnit'
        headers = {
            ':authority': 'sell.souq.com',
            ':method': 'POST',
            ':path': '/create-item/addItemUnit',
            ':scheme': 'https',
            'accept': 'application/json, text/plain, */*',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.8',
            'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'origin': 'https://sell.souq.com',
            'referer': 'https://sell.souq.com/inventory/item-listing/confirmation',
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest',
            'Cookie': self.cookies
        }
        data = {
            'params[item][attributes][gender_en][id_static_value]':'4157',
            'params[item][attributes][gender_en][text_label]':'Girls',
            'params[item][attributes][gender_en][label]':'Targeted Group',
            'params[item][attributes][swimwear_type_en][id_static_value]':'164',
            'params[item][attributes][swimwear_type_en][text_label]':'Bikini Set',
            'params[item][attributes][swimwear_type_en][label]':'Swimwear Type',
            'params[item][attributes][manufacturer_en][id_static_value]':'specify_your_own',
            'params[item][attributes][manufacturer_en][specify_your_own_text_label]':'Specify Your Own',
            'params[item][attributes][manufacturer_en][label]':'Brand',
            'params[item][attributes][manufacturer_en][text_label]':'12345',
            'params[item][attributes][colors_en][label]':'Color',
            'params[item][attributes][colors_en][text_label]':'Alice Blue',
            'params[item][attributes][colors_en][id_static_value]':'62533',
            'params[item][attributes][size_en][label]':'Size',
            'params[item][attributes][size_en][text_label]':'S',
            'params[item][attributes][size_en][id_static_value]':'30746',
            'params[item][categoryTitle]':'Apparel, Shoes & Accessories > Clothing > Swimwear',
            'params[item][descriptions_en]':'<ul class="generatedBullets"><li>Targeted Group : Girls</li><li>Swimwear Type : Bikini Set</li><li>Brand : 12345</li></ul>',
            'params[item][descriptions_ar]':'<ul class="generatedBullets"><li>المجموعة المستهدفة : بنات</li><li>نوع ملابس السباحة : اطقم بيكيني</li><li>Brand : null</li></ul>',
            'params[item][title_item_en]':'12345 Alice Blue Bikini Set For Girls',
            'params[item][title_item_ar]':'12345 اطقم بيكيني اليس بلو -بنات',
            'params[item][isNewItem]':'true',
            'params[item][coverPictureS3]':'https://production-upload-temp-images.s3.amazonaws.com/r8f94bmo26613to1h6me64jgmj5cskp5/487/IMG_0009%20%281%29.JPG',
            'params[item][pictures][0][cover_image]':'https://production-upload-temp-images.s3.amazonaws.com/r8f94bmo26613to1h6me64jgmj5cskp5/487/IMG_0009%20%281%29.JPG',
            'params[itemType]':'487',
            'params[unit][freeShipping]':'yes',
            'params[unit][shippingType]':'pick_up',
            'params[unit][shippingMapping]':'1031###1331###7331###8031###8071',
            'params[unit][amount]':'10',
            'params[unit][price]':'10000',
            'params[unit][sku]':'1258',
            'params[unit][deliveryTime]':'b',
            'params[unit][sellerAddress][firstname]':'Yeling',
            'params[unit][sellerAddress][lastname':'Nii',
            'params[unit][sellerAddress][idCity]':'89',
            'params[unit][sellerAddress][isVerifiedPhone]':'VERIFIED',
            'params[unit][sellerAddress][city]':'Dubai',
            'params[unit][sellerAddress][idCountry]':'1',
            'params[unit][sellerAddress][country]':'UAE',
            'params[unit][sellerAddress][idRegion]':'276',
            'params[unit][sellerAddress][region]':'Ras Al Khor',
            'params[unit][sellerAddress][buildingNo]':'Warehouse No.78',
            'params[unit][sellerAddress][street]':'Ahll Steel Warehouse',
            'params[unit][sellerAddress][isPrimary]':'true',
            'params[unit][sellerAddress][phone]':'971544300184',
            'params[unit][sellerAddress][isSelected]':'true',
            'params[unit][sellerAddress][idCustomerAddress]':'40123558',
            'params[unit][sellerAddress][verificationStatus]':'VERIFIED',
            'params[unit][sellerAddress][$$hashKey]':'object:25916',
            'token':self.token,
        }
        resp = self.session.post(url = url,headers = headers,data=data,verify=False)
        print(resp.content)
        # {"error":false,"result":{"id_unit":"17371700487","is_duplicate":false,"id_tender":"49844165"}}

    def uploadIMG(self):
        url = 'https://sell.souq.com/create-item/uploadImage?subcategory=487'
        headers = {
            'authority': 'sell.souq.com',
            'method': 'POST',
            'path': '/create-item/uploadImage?subcategory=487',
            'scheme': 'https',
            'accept': 'application/json, text/plain, */*',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.8',
            'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryJed452fA0IpVvXnu',
            'origin': 'https://sell.souq.com',
            'referer': 'https://sell.souq.com/inventory/create-item?subcategory=487',
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest',
            'Cookie': 'SCXAT=TXmMjfklhBcN5ExiFfUTZbeaNXleqNyuV7ofdJ8iQ+1506344947897; ab.storage.deviceId.dde4157a-6ed4-4e47-a940-cdd336f179b2=%7B%22g%22%3A%2221acc68d-5bd4-211d-b898-96ff185bb681%22%2C%22c%22%3A1506344943289%2C%22l%22%3A1506344943289%7D; ab.storage.userId.dde4157a-6ed4-4e47-a940-cdd336f179b2=%7B%22g%22%3A%2216178435%22%2C%22c%22%3A1506344947056%2C%22l%22%3A1506344947056%7D; s_cc=true; SCAUAT=eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxNjE3ODQzNSIsImZpcnN0TmFtZSI6IlllbGluZyIsImxhc3ROYW1lIjoiTmlpIiwicm9sZSI6IlNFTExFUiIsInNlbGxlcklkIjoxLjYxNzg0MzVFNywiZ3JvdXBJZCI6MS42MTc4NDM1RTcsImlzcyI6IlNPVVEiLCJpZCI6MS42MTc4NDM1RTcsImV4cCI6MTUwNjc4OTgxOSwidXNlck5hbWUiOiJ1bnBlciIsImlhdCI6MTUwNjc4NjIxOX0.vIxQIwOv6P7TCrAYbZ7YbgrZEZfHqHkHkltH6z38cEc22qPdePDJHTOqsMlG-KJ7qXWtYH_4iu3QYDyc4dLHiFSPDKBnx1zGyHkstpWs7i5vOyiZB1eG30m2C5aclR84tDvb0Lsfx65IfXd-Gph2PkFa2hztmWZOh2lxgYc7zklL9ZGc1Js7XqHUQi4FWZW8760R1iiLuxWET76iXSn3Fch9p1AYm_MtBUw5vOOpEZFbkqoP8rMonjSLpAOwreQqEEAD6cy4wBZA4-WF0rmFcc1AlwSVEo9CJQgTcyW_eCfuIB8Zjl5PGlDeTjgCp7g45DvJMjBJxMefZ_B2Gf0J9bstD1QBw7YXl4J5Ys4LLL73610WWbIExLkZ0P3U-04Gm0rVQ-KCx3lDC6tb8VIqBtv5JYe8qULDW9PzuSVZ9SDtqeZpCLW2VGFwDKwkp18_E16k7Xds7mohDAPCpGvCG58DrcM2zLkm0I3xyQjbPA6JQPK580-FkyAHmvEE2h0YgGMb5CRKJQlKjSfVt7aTIlyHR5e2HiTNq5-c-cj-VjVITI2ItEr1UN3Bo2sLhYrN3PyvyccnXV9ydNp_19JrnA0A9vkYgQKmnFLfFaoasrAlFw8clXa5L9wne8Rdgsi0szVi5BobZK2tDvyc_ejnwPUxfrgDm70U9hnbaKpiYzw; SCAURT=688e2e3995fee09affd37827673f1441; SCAUTT=BEARER; PHPSESSID=kn8qvcshd5f09t43omrqkl7bll88etfe; ab.storage.sessionId.dde4157a-6ed4-4e47-a940-cdd336f179b2=%7B%22g%22%3A%222f830475-2ef5-8120-150a-9d9d3af2568e%22%2C%22e%22%3A1506788008385%2C%22c%22%3A1506784167220%2C%22l%22%3A1506786208385%7D; s_sq=%5B%5BB%5D%5D; PLATEFORMC=ae; PLATEFORML=en; s_fid=3EB96B6B2D980E06-3D5A6FCA435EC20B'
        }
        # files = {
        #     'token': self.token,
        #     'file':('pic.jpg',open(r'C:\Users\drgon\Pictures\iCloud Photos\Downloads\2008\IMG_0009.JPG','rb'),'image/jpeg'),
        #
        # }

        x = """------WebKitFormBoundaryJed452fA0IpVvXnu
Content-Disposition: form-data; name="token"

{token}
------WebKitFormBoundaryJed452fA0IpVvXnu
Content-Disposition: form-data; name="data"

{{}}
------WebKitFormBoundaryJed452fA0IpVvXnu
Content-Disposition: form-data; name="file"; filename="{name}"
Content-Type: image/jpeg
        
{file}
------WebKitFormBoundaryr5W9Fj60vtdVFeTs--""".format(
                token = self.token,
                name = 'IMG_1256.JPG',
                file = open(r'C:\Users\drgon\Pictures\iCloud Photos\Downloads\2008\IMG_0009.JPG','rb').read()
        )
        print(self.cookies)
        m = MultipartEncoder(
            fields={'token': 'TXmMjfklhBcN5ExiFfUTZbeaNXleqNyuV7ofdJ8iQ',
                    'data': '{}',
                    'file': ('IMG_0000009.JPG', open(r'C:\Users\drgon\Pictures\iCloud Photos\Downloads\2008\IMG_0009.JPG','rb'), 'image/jpeg')}
        )
        resp = requests.post(url=url, headers=headers, data=x,verify=False)
        # veFe8PWJGIZoD8FRRVB59qIcfPLLGZ2kAxkmYNNJyr0
        print(resp.headers)
        print(self.token)
        print(resp.content)
        print(resp.url)
        #{"files":[{"name":"IMG_0009 (1).JPG","size":33916,"type":"image\/jpeg","url":"https:\/\/production-upload-temp-images.s3.amazonaws.com\/r8f94bmo26613to1h6me64jgmj5cskp5\/487\/IMG_0009%20%281%29.JPG","thumbnail600X600Url":"https:\/\/production-upload-temp-images.s3.amazonaws.com\/r8f94bmo26613to1h6me64jgmj5cskp5\/487\/thumbnail600X600\/IMG_0009%20%281%29.JPG","thumbnailUrl":"https:\/\/production-upload-temp-images.s3.amazonaws.com\/r8f94bmo26613to1h6me64jgmj5cskp5\/487\/thumbnail\/IMG_0009%20%281%29.JPG","thumbnail80X76Url":"https:\/\/production-upload-temp-images.s3.amazonaws.com\/r8f94bmo26613to1h6me64jgmj5cskp5\/487\/thumbnail80X76\/IMG_0009%20%281%29.JPG","deleteUrl":"https:\/\/uae.souq.com\/ae-en\/offer_listing_images.php?UploadHandler=1&file=IMG_0009%20%281%29.JPG&_method=DELETE&action=add","deleteType":"POST"}]}

    def getOffers(self):
        url = 'https://sell.souq.com/inventory/getOffers'
        headers = {

        }


if __name__ == "__main__":
    test = Souq()
    test.login1()
    test.login()
    # test.getSellerAllowedToListInfo()
    # test.step3()
    # test.offerlisting()
    # test.insert()
    # test.createItem()
    # test.uploadIMG()
    test.uploadIMG()